import os
import sys
import time

import win32serviceutil
import win32service
import win32event
import servicemanager

import winerror

import app_config
from py import server_manager
from py.uitls import WinUtil, PyUtil, FileUtil
from py.uitls.Logger import myLogger
from py.uitls.SManager import ServiceManager


class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = app_config.server_name  # 服务名
    _svc_display_name_ = "Network Port Service"  # 服务在windows系统中显示的名称
    _svc_description_ = "提供本地网络的端口转换。如果禁用该功能，某些应用程序(如家庭组)可能无法正常运行。"  # 服务的描述

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.run = True

    def SvcDoRun(self):
        try:
            myLogger.info("服务运行成功，正常处理数据")
            # CamUtil.init() 这里不是主线程我无法初始化
            server_manager.server_start()
            while 1:
                time.sleep(10)
                myLogger.info("alive")
        except Exception as e:
            myLogger.exception(e)

    def SvcStop(self):
        myLogger.info("service is stop....")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False


def stop_server():
    if not WinUtil.is_admin():
        WinUtil.get_admin()
        return

    sm = ServiceManager(app_config.server_name)
    if not sm.is_stop():
        myLogger.info("服务运行中，停止服务...")
        sm.stop()


def inst_or_update(exe_path):
    temp_argv = sys.argv;
    if not WinUtil.is_admin():
        WinUtil.get_admin()
        return

    sm = ServiceManager(app_config.server_name)

    if not sm.is_exists():
        # 服务不存在则自动注册服务
        sys.argv = [exe_path, '--startup', 'auto', 'install']
        myLogger.info("自动安装服务参数：%s" % (sys.argv,))
        win32serviceutil.HandleCommandLine(PythonService)  # 参数和上述定义类名一致
        myLogger.info("服务安装成功（初始化）！")
    else:
        # 存在服务则更新
        sys.argv = [exe_path, 'update']
        myLogger.info("更新服务参数：%s" % (sys.argv,))
        win32serviceutil.HandleCommandLine(PythonService)  # 参数和上述定义类名一致
        myLogger.info("服务更新成功（初始化）！")

    try:
        sys.argv = [exe_path, 'start']
        myLogger.info("使用命令行启动参数：%s" % (sys.argv,))
        win32serviceutil.HandleCommandLine(PythonService)  # 参数和上述定义类名一致
    except Exception as e:
        myLogger.exception(e)

    try:
        myLogger.info("调用[服务管理]启动")
        sm.start()
    except Exception as e:
        myLogger.exception(e)

    sys.argv = temp_argv;


def handle_command_line():
    if len(sys.argv) == 1:
        # 这段代码必须存在，否则会导致启动服务时1053错误
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            myLogger.info("服务路径(servicemanager)：%s" % evtsrc_dll)
            servicemanager.Initialize(app_config.server_name, evtsrc_dll)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
        except Exception as e:
            myLogger.exception(e)

    else:
        # 正常处理执行的参数命令
        win32serviceutil.HandleCommandLine(PythonService)
        myLogger.info("服务命令执行完成")


if __name__ == '__main__':
    handle_command_line()

# pip install pywin32

# 安装服务
# python PythonService.py install
# 让服务自动启动
# python PythonService.py --startup auto install
# 启动服务
# python PythonService.py start
# 重启服务
# python PythonService.py restart
# 停止服务
# python PythonService.py stop
# 删除/卸载服务
# python PythonService.py remove
